package com.JaMorant.SSM.thc.listener;

import com.JaMorant.SSM.model.live.LiveCourseGoods;
import com.JaMorant.SSM.model.thc.DeliveryConfig;
import com.JaMorant.SSM.model.thc.GoodsConfig;
import com.JaMorant.SSM.model.thc.PddOrder;
import com.JaMorant.SSM.thc.mapper.DeliveryConfigMapper;
import com.JaMorant.SSM.thc.mapper.GoodsConfigMapper;
import com.JaMorant.SSM.thc.mapper.PddOrderMapper;
import com.JaMorant.SSM.vo.thc.PddOrderProductCostVo;
import com.JaMorant.SSM.vo.thc.PddOrderVo;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PddOrderProductCostListener extends AnalysisEventListener<PddOrderProductCostVo> {

    //注入mapper
    @Autowired
    private PddOrderMapper pddOrderMapper;

    @Autowired
    private DeliveryConfigMapper deliveryConfigMapper;

    @Autowired
    private GoodsConfigMapper goodsConfigMapper;

    private Map<String, BigDecimal> provinceToPriceMaps;
    private Map<String, BigDecimal> goodsNoToPriceMaps;

    private Set<String> goodsNos;


    @PostConstruct
    void init() {
        QueryWrapper<DeliveryConfig> deliveryConfigQueryWrapper = new QueryWrapper<>();
        List<DeliveryConfig> deliveryConfigs = deliveryConfigMapper.selectList(deliveryConfigQueryWrapper);
        provinceToPriceMaps = deliveryConfigs.stream().collect(Collectors.toMap(DeliveryConfig::getProvince, DeliveryConfig::getPrice));

        QueryWrapper<GoodsConfig> goodsConfigQueryWrapper = new QueryWrapper<>();
        List<GoodsConfig> goodsConfigs = goodsConfigMapper.selectList(goodsConfigQueryWrapper);
        goodsNoToPriceMaps = goodsConfigs.stream().collect(Collectors.toMap(GoodsConfig::getGoodsNo, GoodsConfig::getPrice));
        goodsNos = goodsConfigs.stream().map(GoodsConfig::getGoodsNo).collect(Collectors.toSet());
    }

    //一行一行，从第二行
    // erp 导出数据，如果用户购买多分，会有问题，需要解决快递拆单
    @Override
    public void invoke(PddOrderProductCostVo pddOrderVo, AnalysisContext analysisContext) {
        if (pddOrderVo == null || StringUtils.isBlank(pddOrderVo.getOrderNo())) {
            return;
        }

        LambdaQueryWrapper<PddOrder> pddOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pddOrderLambdaQueryWrapper.eq(PddOrder::getOrderNo, pddOrderVo.getOrderNo())
                .eq(PddOrder::getBusinessType, "生产成本");

        PddOrder pddOrder = pddOrderMapper.selectOne(pddOrderLambdaQueryWrapper);
        // 新增或者修改订单表
        buildProductCostPddOrder(pddOrder, pddOrderVo);
        //添加 快递
        calculationDeliveryCost(pddOrderVo);
    }

    private void buildProductCostPddOrder(PddOrder pddOrder, PddOrderProductCostVo pddOrderVo) {
        boolean isNew = false;
        if (pddOrder == null) {
            isNew = true;
            pddOrder = new PddOrder();
            pddOrder.setOrderNo(pddOrderVo.getOrderNo());
            pddOrder.setBusinessType("生产成本");
        }

        String defaultDesc = "商品编码为：" + pddOrderVo.getGoodsNo() + ",购买数量为：" + pddOrderVo.getStock() + ",所属省份：" + pddOrderVo.getProvince();
        // 当前商品编码不在当前配置的商品编码中，返回
        if (!goodsNos.contains(pddOrderVo.getGoodsNo())) {
            pddOrder.setDes(defaultDesc);
            pddOrder.setPrice(BigDecimal.ZERO);
            log.info("订单编号：" + pddOrderVo.getOrderNo() + " 商品编码为：" + pddOrderVo.getGoodsNo() + ",购买数量为：" + pddOrderVo.getStock() + ",所属省份：" + pddOrderVo.getProvince());
        } else {
            BigDecimal price = goodsNoToPriceMaps.get(pddOrderVo.getGoodsNo()).multiply(pddOrderVo.getStock());

            pddOrder.setPrice(price.negate());
        }

        if (isNew) {
            pddOrder.setDes(defaultDesc);
        } else {
            pddOrder.setDes(pddOrder.getDes() + System.lineSeparator() + defaultDesc);
        }

        // 当前订单生产成本
        BigDecimal currentProductCost = calculationCurrentProductCost(pddOrderVo);
        if (isNew) {
            pddOrder.setPrice(currentProductCost);
        } else {
            pddOrder.setPrice(currentProductCost.add(pddOrder.getPrice()));
        }

        if (isNew) {
            pddOrderMapper.insert(pddOrder);
        } else {
            pddOrderMapper.updateById(pddOrder);
        }
    }

    private BigDecimal calculationCurrentProductCost(PddOrderProductCostVo pddOrderVo) {
        // 当前商品编码不在当前配置的商品编码中，返回
        if (!goodsNos.contains(pddOrderVo.getGoodsNo())) {
            return BigDecimal.ZERO;
        }
        BigDecimal price = goodsNoToPriceMaps.get(pddOrderVo.getGoodsNo()).multiply(pddOrderVo.getStock());
        if (price == null) {
            return BigDecimal.ZERO;
        }
        return price.negate();
    }

    private void calculationDeliveryCost(PddOrderProductCostVo pddOrderProductCostVo) {
        if (StringUtils.isBlank(pddOrderProductCostVo.getDeliveryCompany())) {
            return;
        }
        if (!pddOrderProductCostVo.getDeliveryCompany().contains("极兔")) {
            log.info("当前订单号：[{}] 快递公司非极兔", pddOrderProductCostVo.getOrderNo());
            return;
        }

        LambdaQueryWrapper<PddOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PddOrder::getOrderNo, pddOrderProductCostVo.getOrderNo()).eq(PddOrder::getBusinessType, "运费成本");

        boolean isNew = false;
        PddOrder pddOrder = pddOrderMapper.selectOne(lambdaQueryWrapper);
        if (pddOrder == null) {
            isNew = true;
            pddOrder = new PddOrder();
            pddOrder.setOrderNo(pddOrderProductCostVo.getOrderNo());
            pddOrder.setBusinessType("运费成本");
        }
        // 当前订单快递费
        BigDecimal currentDeliveryCost = calculationCurrentDeliveryCost(pddOrderProductCostVo);
        // 当前快递费为0，不需要重新计算
        if (currentDeliveryCost.compareTo(BigDecimal.ZERO) == 0) {
            return;
        }


        String defaultDesc = "商品编码为：" + pddOrderProductCostVo.getGoodsNo() + ",购买数量为：" + pddOrderProductCostVo.getStock() + ",所属省份：" + pddOrderProductCostVo.getProvince();
        if (isNew) {
            pddOrder.setPrice(currentDeliveryCost);
            pddOrder.setDes(defaultDesc);
        } else {
            String des = pddOrder.getDes() + defaultDesc;
            pddOrder.setPrice(currentDeliveryCost.add(pddOrder.getPrice()));
            pddOrder.setDes(des);
        }
        if (isNew) {
            pddOrderMapper.insert(pddOrder);
        } else {
            pddOrderMapper.updateById(pddOrder);
        }
    }

    /**
     * 计算当前订单号快递费用
     *
     * @param pddOrderProductCostVo
     * @return
     */
    public BigDecimal calculationCurrentDeliveryCost(PddOrderProductCostVo pddOrderProductCostVo) {
// 快递是极兔，说明一定有快递费
        //试用装 价格统一为2.1
        if (checkIsShiYong(pddOrderProductCostVo.getGoodsNo())) {
            // 固定快递费
            BigDecimal bigDecimal = new BigDecimal("2.1");
            return bigDecimal.negate();
        } else {
            // 未获取到省份，默认快递费为3.5
            if (StringUtils.isBlank(pddOrderProductCostVo.getProvince())) {
                BigDecimal bigDecimal = new BigDecimal("3.5");
                return bigDecimal.negate();
            } else {
                // 获取到省份，根据省份计算运费
                BigDecimal deliveryPrice = provinceToPriceMaps.get(pddOrderProductCostVo.getProvince());
                if (deliveryPrice != null) {
                    return deliveryPrice.negate();
                }
                log.info("当前订单号:[{}] 未获取到运费，请核查", pddOrderProductCostVo.getOrderNo());
                return BigDecimal.ZERO;
            }
        }
    }

    private boolean checkIsShiYong(String goodsNo) {
        if (goodsNo.startsWith("cp")) {
            return false;
        }
        if (goodsNo.startsWith("XJH-") && (goodsNo.contains("-5") || goodsNo.contains("-10") || goodsNo.contains("-2") || goodsNo.contains("-20") || goodsNo.contains("-15"))) {
            return true;
        }
        return false;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
